import accounts.com.Accounts_Service
import accounts.com.Accounts
import gforgeclient.GForgeAPI;
import gforgeclient.GForgeAPIPortType;
import gforgeclient.GForgeAPI_Impl;
import gforgeclient.User;

class UserController {

	def index = { redirect(action:list,params:params) }
	
	// the delete, save and update actions only
	// accept POST requests
	def allowedMethods = [delete:'POST', save:'POST', update:'POST']
	
	def list = {
		if(!params.max)params.max = 10
		[ userList: User.list( params ) ]
	}
	
	def show = {
		[ user : User.get( params.id ) ]
	}
	
	def delete = {
		def user = User.get( params.id )
		if(user) {
			if( user.loanings.size() != 0 ) {
				flash.message = "You cannot delete a user when he/she is associated to some loaning(s).  Please delete the loaning(s) the user is associated to before deleting him/her."
				redirect(action:show,id:user.id)
			}else{
				user.delete()
				flash.message = "User ${params.id} deleted."
				redirect(action:list)
			}
		}
		else {
			flash.message = "User not found with id ${params.id}"
			redirect(action:list)
		}
	}
		
	def edit = {
		def user = User.get( params.id )
		
		if(!user) {
			flash.message = "User not found with id ${params.id}"
			redirect(action:list)
		}
		else {
			return [ user : user ]
		}
	}
	
	def update = {
		def user = User.get( params.id )
		if(user) {
			user.properties = params
			if(user.save()) {
				redirect(action:show,id:user.id)
			}
			else {
				render(view:'edit',model:[user:user])
			}
		}
		else {
			flash.message = "User not found with id ${params.id}"
			redirect(action:edit,id:params.id)
		}
	}
	
	def create = {
		def user = new User()
		user.properties = params
		return ['user':user]
	}
	
	def save = {
		def user = new User()
		user.properties = params
		if(user.save()) {
			redirect(action:show,id:user.id)
		}
		else {
			render(view:'create',model:[user:user])
		}
	}
		
	def login = {
		if (session.user) {  
			//redirect(action:show,id:session.user.id)
			//	redirect(controller:'book', action:'list')
		} else {
			return ['user':null]
		}
	}
	
	def logout = {
		if (session.user) {
                    println "doing logout"
                    try {

                    def Accounts_Service service = new Accounts_Service();
                    def Accounts accountsClient = service.getAccountsHttpPort();
                    accountsClient.loggout(session.idSession)

                    libraryLogout()
                    devicesLogout()
                    gforgeLogout()
                    newsLogout()
                    //println "Usuario ${session.login} deslogado."
                    } catch (Exception e) {
                        println "exception in logout"
                    }
                    session.user = null
                    redirect(uri:"")
		}
	}
	
	def validate = { login, pass ->
		//login: cayo
                //password: uQ9kmN4F
		
		//      ----------------USANDO o validate do embeddedNews---------------------------------
		
		// trying connect to webservice accounts
		try {
			println "starting the authentication"
			def Accounts_Service service = new Accounts_Service();
			def Accounts accountsClient = service.getAccountsHttpPort();			
			def idSession = accountsClient.loggon(login, pass)			
			println "idSession = ${idSession}"


			if( idSession != null ){
                            session.idSession = idSession
                            session.login = login
                            session.password = pass
                            
			} else {
                            return false
                        }
                        
		} catch (Exception e) {			
			flash.message = e.getMessage()
			return false	
		}

		return true
	}
		
	def handleLogin = {		
		if(validate(params.login, params.password)){
			session.user = params.login
			//session.login = login
                        flash.message = "You are logged now!"
			render(view:'/user/principal')
			
		} else {
                        flash.message = "Invalid login or password!"
			render(view:'/index')
		}		
	}
	
	def register = {
		def user = new User()
		user.properties = params
		return ['user':user]
	}
	
	def handleRegistration = {
		def user = new User(params)
		if (params.password != params.confirm) {
			user.validate()
			user.password = null
			user.confirm = null
			render(view:'register',model:[user:user])
		} else {
			user.password = params.password.encodeAsPassword()
			user.confirm = ""
			if (user.save()) {
				redirect(controller:'user', action:'list')
			} else {
				user.password = null
				user.confirm = null
				flash.user = user
				render(view:'register',model:[user:user])
			}
		}
	}	
}